package wn.lizzy.essay.service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Strings;

import wn.lizzy.essay.entity.Text;
import wn.lizzy.essay.entity.User;
import wn.lizzy.essay.repository.ClassificationRepository;
import wn.lizzy.essay.repository.TextRepository;
import wn.lizzy.essay.repository.TypeRepository;
import wn.lizzy.essay.repository.UserRepository;

@Service
public class TextService {
	@Resource
	private ClassificationRepository classificationRepository;
	@Resource
	private TextRepository textRepository;
	@Resource 
	private TypeRepository typeRepository;
	@Resource 
	private UserRepository userRepository;
	
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public Page<Text> getTextList(Map<String, Object> queryPrams, Pageable pageable) {
		return textRepository.findAll((root, query, cb) -> {
			Predicate predicate = cb.conjunction();
			List<Expression<Boolean>> expressions = predicate.getExpressions();
			
			// *****************  此处添加约束条件   start ***************************
			int valid = (int)queryPrams.get("valid");
			String title = (String)queryPrams.get("title");
			Date stime = (Date)queryPrams.get("stime");
			Date etime = (Date)queryPrams.get("etime");
			
			if(!Strings.isNullOrEmpty(title)) {
				expressions.add(cb.like(root.<String> get("title"), "%"+title+"%"));
			}
			else if (stime != null) {
				expressions.add(cb.greaterThanOrEqualTo(root.get("createtime"), stime));
			}
			else if (etime != null) {
				// 默认时间是当前0点，所以加上一天
				Calendar eCal = Calendar.getInstance();
				eCal.setTime(etime);
				eCal.add(Calendar.DAY_OF_MONTH, 1);
				
				expressions.add(cb.lessThan(root.get("createtime"), eCal.getTime()));
			}else{
				expressions.add(cb.equal(root.get("valid"), valid));
			}
			// *****************  此处添加约束条件   end ***************************
			Order[] order = new Order[1];
			order[0] = cb.desc(root.get("updatetime"));
			query.orderBy(order);
			return predicate;
		} , pageable);
	}
	
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public Text getText(Long uid) {
		return textRepository.findOne(uid);
	}
	
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { Exception.class })
	public void saveText(User currentUser, Text textnew, Long classid, Long typeid) throws Exception {
		Text text = new Text();
		text.setTitle(textnew.getTitle());
		text.setIntroduction(textnew.getIntroduction());
		text.setThumbnail(textnew.getThumbnail());
		text.setClassification(classificationRepository.findOne(classid));
		text.setType(typeRepository.findOne(typeid));
		text.setCreatetime(new Date());
		text.setCreateuser(currentUser);
		text.setUpdatetime(new Date());
		text.setUpdateuser(currentUser);
		text.setContent(textnew.getContent());
		text.setValid(textnew.getValid());
		text.setClicknum(0L);
		textRepository.save(text);
	}
	
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { Exception.class })
	public void updateText(User currentUser, Long uid, Text textnew, Long classid) throws Exception {
		Text text =textRepository.findOne(uid);
		text.setTitle(textnew.getTitle());
		text.setIntroduction(textnew.getIntroduction());
		text.setThumbnail(textnew.getThumbnail());
		text.setClassification(classificationRepository.findOne(classid));
		text.setUpdatetime(new Date());
		text.setUpdateuser(currentUser);
		text.setContent(textnew.getContent());
		textRepository.save(text);
	}
	
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { Exception.class })
	public void updateValid(User currentUser, Long uid, int valid) throws Exception {
		Text text =textRepository.findOne(uid);
		text.setUpdatetime(new Date());
		text.setUpdateuser(currentUser);
		text.setValid(valid);
		textRepository.save(text);
	}
	
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { Exception.class })
	public void deleteText(Long uid) throws Exception {
		textRepository.delete(uid);
	}
}
